package com.baidu.iit.pxp.behavior;

import com.baidu.iit.pvm.delegate.ActivityExecution;
import com.baidu.iit.pvm.runtime.InterpretableExecution;
import com.baidu.iit.pxp.entity.ExecutionEntity;

/**
 * User: huangweili
 * Date: 14-4-27
 * Time: 上午9:43
 */
public class AbstractBpmnActivityBehavior extends FlowNodeActivityBehavior {

    protected MultiInstanceActivityBehavior multiInstanceActivityBehavior;


    protected void leave(ActivityExecution execution) {

        if (!hasLoopCharacteristics()) {
            super.leave(execution);
        } else if (hasMultiInstanceCharacteristics()){
            multiInstanceActivityBehavior.leave(execution);
        }
    }

    protected boolean hasLoopCharacteristics() {
        return hasMultiInstanceCharacteristics();
    }

    protected boolean hasMultiInstanceCharacteristics() {
        return multiInstanceActivityBehavior != null;
    }

    public MultiInstanceActivityBehavior getMultiInstanceActivityBehavior() {
        return multiInstanceActivityBehavior;
    }

    public void setMultiInstanceActivityBehavior(MultiInstanceActivityBehavior multiInstanceActivityBehavior) {
        this.multiInstanceActivityBehavior = multiInstanceActivityBehavior;
    }

    @Override
    public void signal(ActivityExecution execution, String signalName, Object signalData) throws Exception {
        if("compensationDone".equals(signalName)) {
            signalCompensationDone(execution, signalData);
        } else {
            super.signal(execution, signalName, signalData);
        }
    }

    protected void signalCompensationDone(ActivityExecution execution, Object signalData) {
        if(execution.getExecutions().isEmpty()) {
            if(execution.getParent() != null) {
                ActivityExecution parent = execution.getParent();
                ((InterpretableExecution)execution).remove();
                ((InterpretableExecution)parent).signal("compensationDone", signalData);
            }
        } else {
            ((ExecutionEntity)execution).forceUpdate();
        }

    }

}
